package com.yunyike.wx.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yunyike.wx.common.WeChat;
import com.yunyike.wx.common.WeiXinPropertiesUtil;
import com.yunyike.wx.service.IWeixinKitService;
import com.yunyike.wx.utils.DateUtil;

/**
 * 微信基本信息接口实现类
 * 
 * @author wenjian
 * 
 */
@Service("weixinKitServiceImpl")
public class WeixinKitServiceImpl implements IWeixinKitService {

	private final Logger log = LoggerFactory.getLogger(getClass());
	
	public String getAccessTime() {
		return WeiXinPropertiesUtil.getAccessExpires();
	}

	public String getAccessToken() {
		log.info("开始检查access_token,判断有没有过期");
		String accessToken = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			accessToken = WeiXinPropertiesUtil.getAccessToken();
			String lastTime = WeiXinPropertiesUtil.getAccessExpires();
			log.info("读取配置access_token={},上次同步时间={}", accessToken, lastTime);
			Date accessExpires = DateUtil.parseDateTime(lastTime);
			Date now = new Date();
			if (now.getTime() > accessExpires.getTime()) {
				log.info("获取access_token,判断出已过期");
				// 获取access_token
				try {
					map = WeChat.getAccessToken();
					accessToken = map.get("access_token").toString();
				} catch (Exception e) {
					throw new Exception("获取access_token失败" + map);
				}
				accessExpires = new Date(now.getTime() + 7200000);
				String nextTime = DateUtil.formatDateTime(accessExpires);
				log.info("获取完access_token{}后,更新配置上次同步时间={}",accessToken, nextTime);
				// 更新AccessToken和AccessExpires
				WeiXinPropertiesUtil.setAccessToken(accessToken);
				WeiXinPropertiesUtil.setAccessExpires(nextTime);
			} else {
				log.info("获取access_token,判断出未过期");
			}
		} catch (Exception e) {
			log.error("获取access_token失败{}",map);
		}
		return accessToken;
	}

	public String getAppid() {
		return WeiXinPropertiesUtil.getAppId();
	}

	public String getAppsecret() {
		return WeiXinPropertiesUtil.getAppSecret();
	}

	public String getToken() {
		return WeiXinPropertiesUtil.getToken();
	}

	public String getPartnerkey() {
		return WeiXinPropertiesUtil.getPartnerKey();
	}

	public String getMchId() {
		return WeiXinPropertiesUtil.getMerchantNo();
	}
}
